import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {
    private DatagramSocket socket = null;
    private String IP;
    private int Port;
    public UdpClient(String IP,int Port) throws SocketException {
        //实例化对象并且添加属性
        socket = new DatagramSocket();
        this.IP = IP;//IP地址
        this.Port = Port;//端口号
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true){
            //读取输入内容
            String request = scanner.next();
            //创建数据缓存区，准备发送数据
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(this.IP),this.Port);
            //发送数据
            socket.send(requestPacket);
            //再次创建数据缓存区，准备接收数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            //接收数据
            socket.receive(responsePacket);
            //转化为字符串类型
            String response = new String(responsePacket.getData(),0, responsePacket.getLength());
            //打印接收到的内容
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient Client = new UdpClient("127.0.0.1",9090);
        Client.start();
    }
}
